AddCSLuaFile("cl_init.lua")
AddCSLuaFile("shared.lua")
include('shared.lua')

SWEP.Weight = 8
SWEP.AutoSwitchTo = false
SWEP.AutoSwitchFrom = false

SWEP.Receiver = nil
SWEP.Pointing = false
SWEP.MIndex = 0
SWEP.Present = false

function SWEP:Initialize()
	self.Pointing = false
end

function SWEP:Reload()
	
end

function SWEP:PrimaryAttack()
	if(self.Receiver && self.Receiver:IsValid() && self.Receiver.EnergySupply)then
		self.Pointing = !self.Pointing
		self.Weapon:SetNWBool("Active", self.Pointing)
	end
end

function SWEP:SecondaryAttack()
	local trace = self.Owner:GetEyeTrace()
	if (trace.Entity:GetClass() == "personal_ore_receiver") then
		self.Receiver = trace.Entity
		self.Present = false
		self.MIndex = 0
		
		for k,Miner in pairs(self.Receiver.ActiveMiners) do
			if Miner == self.Entity then
				self.Present = true
				self.Owner:PrintMessage( HUD_PRINTTALK, "You're already linked to the Receiver!" )
				return true
			end
		end
		
		if #self.Receiver.ActiveMiners < 4 and self.Present == false then
			self.MIndex = #self.Receiver.ActiveMiners + 1
			
			self.Receiver.ActiveMiners[self.MIndex] = 0
			
			self.Owner:PrintMessage( HUD_PRINTTALK, "Linked Sucessfully." )
		else
			self.Owner:PrintMessage( HUD_PRINTTALK, "Cannot exceed 4 Miners per Receiver!" )
			self.Receiver = nil
		end
		return true
	end
end

function SWEP:Think()
	if self.Receiver and ValidEntity(self.Receiver) then
		if self.Pointing then
			local pos = self.Owner:GetShootPos()
			local ang = self.Owner:GetAimVector()
			local tracedata = {}
			tracedata.start = pos
			tracedata.endpos = pos+(ang*128)
			tracedata.filter = self.Owner
			local trace = util.TraceLine(tracedata)
		
			self.Receiver.Asteroids[self.MIndex] = trace.Entity
			self.Receiver.ActiveMiners[self.MIndex] = 1
		else
			self.Receiver.Asteroids[self.MIndex] = nil
			self.Receiver.ActiveMiners[self.MIndex] = 0
		end
	end
end

function SWEP:OnRemove()
	if self.Receiver and ValidEntity(self.Receiver) then
		self.Receiver.ActiveMiners[self.MIndex] = nil
	end
end
